//index.js
//获取应用实例
const app = getApp();
const ctx = wx.createCanvasContext("myCanvas");
const db = wx.cloud.database()
const _ = db.command

Page({
  data: {
    width: 0, //手机的宽度
    left: 0, //canvas 的左边距
    canvas_w: 0,
    type: 1,
    url:''
  },
  onLoad(obj) {
    console.log(obj);
    db.collection('shop_product').where({
      _id: _.eq(obj.data)
    }).get().then(res => {
      console.log(res);
      //type 1：商品详情进入   2：表示分销店铺  0：首页
      this.setData({
        type: obj && obj.type ? obj.type : 1,
        data: res.data
      });
      if (obj.type == 1) {
        this.product(); //绘画店铺海报图
      }
      if (obj.type == 2) {
        // this.fxShop();
      }

    })
  },
  product() {
    this.dragBg();
    this.dragPicture(); //绘制商品图片
  },
  //分销店铺
  fxShop() {
    this.dragBg();
    this.dragShopPicture();
  },
  dragBg() {
    let info = {};
    //判断 基础库版本
    if (!wx.getSystemInfo) {
      wx.showModal({
        title: "提示",
        content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
      });
    }
    wx.getSystemInfo({
      success: res => {
        const canvas_w = res.windowWidth - 75;
        this.setData({
          left: 0,
          canvas_w: canvas_w,
          width: res.windowWidth,
          height: res.windowHeight
        });
      }
    });
  },
  //商品详情
  dragPicture() {
    let data = this.data.data[0];
    let img_str = data.img_url[0];
  
    wx.cloud.downloadFile({
      fileID: img_str,
      success: res => {
        if (res) {
          let path = res.tempFilePath;
          wx.getImageInfo({
            src: path,
            success: json => {
              if (json) {
                const canvas_w = this.data.canvas_w;
                const p_left = (canvas_w - 183) / 2;
                //绘制上半部分的灰色
                ctx.setFillStyle("#f5f5f5");
                ctx.fillRect(0, 0, 600, 32.5);
                //绘制下面白色
                ctx.setFillStyle("#ffffff");
                ctx.fillRect(0, 32.5, 600, 390);
                //绘制中间图片并有阴影
                //绘制中间图片并有阴影
                ctx.setFillStyle("#ffffff");
                ctx.setShadow(0, 6, 12, "rgba(0,0,0,0.2)");
                ctx.fillRect(p_left, 0, 183, 183);
                ctx.draw();
                ctx.drawImage(path, p_left, 0, 183, 183);
                this.dragName(data, p_left); //绘制名称或活动口号
                this.qrcode(); //绘制二维码
                this.wxFont(); //微信扫码查看
              }
            }
          });
        }
      },
      fail: error => {
        console.log(error);
      }
    });
  },
  //店铺
  dragShopPicture() {
    let img_str = "";
    let url = "";
    img_str = "1";
    url = "2";
    wx.downloadFile({
      url: url,
      success: res => {
        if (res) {
          let path = res.tempFilePath;
          wx.getImageInfo({
            src: path,
            success: json => {
              if (json) {
                const canvas_w = this.data.canvas_w;
                const p_left = (canvas_w - 183) / 2;
                //绘制上半部分的灰色
                ctx.drawImage(path, 0, 0, 300, 300);
                this.dragTitle(); //绘制分销店铺词的名称或口号
                this.qrcode(); //绘制二维码
              }
            }
          });
        }
      }
    });
  },
  //绘制分销店铺词的名称或口号
  dragTitle() {
    const text = "一个上平的名称是那么的长吗那么长的明智么长的明智11";
    let text1 = "";
    let text2 = "";
    if (text.length > 17) {
      text1 = text.substring(0, 17);
      text2 = text.substring(18, text.length);
    } else {
      text1 = text;
    }
    ctx.setFontSize(17);
    ctx.setFillStyle("#333333");

    if (text1) {
      ctx.fillText(text1, 0, 325);
    }

    if (text2) {
      ctx.fillText(text2, 0, 345);
    }
    ctx.draw(true);
  },
  dragName(data, p_left) {
    // 0表示正常商品,1表示分销,2表示团购,3表示秒杀,4表示砍价
    ctx.setFillStyle("#ff5757");
    ctx.fill();
    ctx.draw(true);
    const text = data.name;
    let text1 = "";
    let text2 = "";
    if (text.length > 15) {
      text1 = text.substring(0, 15);
      text2 = text.substring(16, text.length);
    } else {
      text1 = text;
    }
    ctx.setFontSize(17);
    ctx.setFillStyle("#333333");
    const canvas_w = this.data.canvas_w;
    if (text1) {
      ctx.setTextAlign("center");
      ctx.fillText(text1, canvas_w / 2, 210);
    }
    if (text2) {
      ctx.setTextAlign("center");
      ctx.fillText(text2, canvas_w / 2, 227);
    }
    ctx.draw(true);
    ctx.setTextAlign("center");
    ctx.setFontSize(32);
    ctx.setFillStyle("#ff5757");
    const price = data.price;
    ctx.fillText(`￥${price}`, canvas_w / 2, 260);
    ctx.draw(true);
  },

  qrcode() {

    const id = this.data.data[0]._id;
    wx.cloud.callFunction({
      name: 'getImage',   // 云函数名称
      data: {    // 小程序码所需的参数
        page: "pages/shop/product/product-detail/index",
        id: id,
      },
      complete: res => {
        console.log('callFunction test result: ', res)
        this.setData({    // 获取返回的小程序码
          xcxCodeImageData: res.result,
        })
        wx.getImageInfo({
          src: res.result.fileID,
          success: res => {
            if (res) {
              const type2 = this.data.type;
              const canvas_w = this.data.canvas_w;
              const p_left = (canvas_w - 90) / 2;
              if (type2 == 1) {
                ctx.drawImage(res.path, p_left, 278, 90, 90);
                ctx.draw(true);
              }
              if (type2 == 2) {
                ctx.drawImage(res.path, p_left, 348, 90, 90);
                ctx.draw(true);
              }
            }
          },
          fail: res => {
            console.log(res);
          }
        });

      }
    })



  },
  wxFont() {
    const canvas_w = this.data.canvas_w;
    ctx.setFontSize(12);
    ctx.setFillStyle("#8a8a8a");
    ctx.fillText("微信扫码查看", canvas_w / 2, 390);
    ctx.draw(true);
  },
  saveImg() {
    const that = this;
    wx.getSetting({
      success(res) {
        const width = that.data.width;
        const height = that.data.height;
        const endHeight = height - 35;
        wx.authorize({
          scope: "scope.writePhotosAlbum",
          success(res) {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: width,
              height: endHeight,
              destWidth: width,
              destHeight: endHeight,
              canvasId: "myCanvas",
              success: function (res) {
                wx.getImageInfo({
                  src: res.tempFilePath,
                  success: function (json) {
                    that.downImg(json.path);
                    return;
                  }
                });
              }
            });
          },
          fail() { },
          complete() { }
        });
      }
    });
  },
  downImg(path) {
    wx.saveImageToPhotosAlbum({
      filePath: path,
      success: function (res) {
        wx.showModal({
          title: "提示",
          content: "保存图片成功",
          showCancel: false
        });
      },
      fail: function (res) {
        wx.showModal({
          title: "保存图片失败",
          content: res.errMsg,
          showCancel: false
        });
      }
    });
  },
  //分享数据
  onShareAppMessage() {
    const data = this.data.data[0];
    let pid = 0;
    const fxUser = wx.getStorageSync("fxUser");
    pid = fxUser ? fxUser.id : 0
    let url = `pages/shop/product/product-detail/index?id=${data._id}&pid=${pid}`;
    return {
      title: data.name,
      path: url
    };
  }
});
